package com.xxx.myapplication

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.google.gson.Gson
import okhttp3.*
import java.io.IOException


class MainActivity : AppCompatActivity(), View.OnClickListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<Button>(R.id.btnPick1).setOnClickListener(this)
        findViewById<Button>(R.id.btnPick2).setOnClickListener(this)
        findViewById<Button>(R.id.btnPick3).setOnClickListener(this)
        findViewById<Button>(R.id.btnPick4).setOnClickListener(this)
        findViewById<Button>(R.id.btnPick5).setOnClickListener(this)
        findViewById<Button>(R.id.btnPick6).setOnClickListener(this)
    }

    /**
     * 获取天气数据
     */
    private fun getWeatherData(cityCode: Int) {
        Thread {
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("https://restapi.amap.com/v3/weather/weatherInfo?city=$cityCode&key=67c96e7789d4503b478eb93d8a36ff84")
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call?, e: IOException?) {}

                override fun onResponse(call: Call?, response: Response?) {
                    val json = response?.body()?.string()
                    val data = Gson().fromJson(json, WeatherData::class.java)
                    runOnUiThread {
                        if (data.status=="1"){
                            findViewById<TextView>(R.id.tvWeather).text =
                                data.lives[0].province.plus(data.lives[0].city + ":" + data.lives[0].weather)
                        }else{
                            Toast.makeText(this@MainActivity,data.info,Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
        }.start()
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.btnPick1 ->
                getWeatherData(110000)
            R.id.btnPick2 ->
                getWeatherData(310000)
            R.id.btnPick3 ->
                getWeatherData(440100)
            R.id.btnPick4 ->
                getWeatherData(440300)
            R.id.btnPick5 ->
                getWeatherData(320500)
            R.id.btnPick6 ->
                getWeatherData(210100)
        }
    }
}